<?php
//员工
namespace app\crm\controller;

use app\crm\model\Sn;
use app\crm\model\StaffAccessory;
use think\Db;
use think\Request;
use think\Exception;
use app\crm\model\Staff as StaffModel;
use weworkapi\api\datastructure\user\User;
use weworkapi\api\src\API;


class Staff extends \CrmController
{
    public function text(){

        $list =  $this->qiyeweixin->UserGet('zhangsan2');

        p($list);


    }
    /**
     * 员工列表接口
     */
    public function index(Request $request){
        $StaffModel = new \app\crm\model\Staff();

        try {
            $params = delToken($request->get());

            $data = $StaffModel->search($params);


            $this->successTerminate($data);
        } catch (Exception $e) {
            $this->serverErrorTerminate($e->getMessage());
        }
    }

    /**
     * 员工简单列表接口
     */
    public function easy(Request $request){
        $StaffModel = new \app\crm\model\Staff();

        try {
            $params = delToken($request->get());

            $data = $StaffModel->easySearch($params);

            $this->successTerminate($data);
        } catch (Exception $e) {
            $this->serverErrorTerminate($e->getMessage());
        }
    }
     public function easydown(Request $request){
        $StaffModel = new \app\crm\model\Staff();

        try {
            $params = delToken($request->get());

            $data = $StaffModel->easySearchDown($params);
            foreach ($data as $k => $v) {
                # code...
                $data[$k]["department_name"]=db("client_staff_relevance")->alias("a")->join("sh_client b","a.client_id=b.client_id")->where("staff_id='{$v["staff_id"]}'")
                ->value("client_name");
            }
            $this->successTerminate($data);
        } catch (Exception $e) {
            $this->serverErrorTerminate($e->getMessage());
        }
    }

    /**
     * 新增员工接口
     */

    public function save(Request $request){
        $params = delToken($request->param());
        try {
//判断是否是唯一
            $SN  = new Sn();
            $snS = $SN->getSn('YG');
            $params['staff_id'] = $snS['0'];
            $StaffModel = new StaffModel();


            $user = new User();
            {
                $user->userid = $params['staff_id'];
                $user->name = $params['staff_name'];//名称
                $user->mobile = $params['phone'];//手机
                $user->department = array($params['department_id']);//部门
                $user->position = $params['duty'];//职位
                $user->gender = $params['sex'];//性别
            }
            $this->qiyeweixin->UserCreate($user);


            $password = md5('123456');
            $params['entry_time'] = strtotime($params['entry_time']);
            $params['salt'] = $StaffModel->generateSalt();
            $params['password'] = md5( $password. $params['salt']);
            $params['is_downstream'] = 1;
            $StaffModel->data($params)->allowField(true)->save();
            $ID = $StaffModel->getLastInsID();
            //新增附件
            if(!empty($params['accessory'])){
                $accessory = $params['accessory'];
                $StaffAccessoryModel = new StaffAccessory();
                $StaffAccessoryDb = $StaffAccessoryModel->StaffAccessoryDb();
                foreach ($accessory as $v1){
                    $arrAccessory = explode('|',$v1);
                    $addOrderAccessory['accessory_url'] = $arrAccessory[0];
                    $addOrderAccessory['accessory_name'] =$arrAccessory[1];
                    $addOrderAccessory['staff_id'] = $ID;
                    $StaffAccessoryDb->insert($addOrderAccessory);
                }
            }
            $this->successTerminate();
        } catch (Exception $e) {
            $this->serverErrorTerminate($e->getMessage());
        }
    }
    /**
     * 删除员工接口
     */

    public function delete(Request $request){
        $params = delToken($request->param());
        try {

            $StaffModel = new StaffModel();
            $where['staff_id'] = $params['staff_id'] ;
            $this->qiyeweixin->UserDelete($params['staff_id']);
            $StaffModel->where($where)->delete();
            $this->successTerminate();
        } catch (Exception $e) {
            $this->serverErrorTerminate($e->getMessage());
        }
    }
    /**
     * 员工更改部门接口
     */

    public function updateDepartment(Request $request){
        $params = delToken($request->param());
        try {
            $StaffModel = new StaffModel();
            $user = new User();
            {
                $user->userid = $params['staff_id'];
                $user->department = array($params['department_id']);
            }
            $this->qiyeweixin->UserUpdate($user);
            $where['staff_id'] = $params['staff_id'] ;
            $StaffModel->where($where)->update(['department_id'=>$params['department_id']]);
            $this->successTerminate();
        } catch (Exception $e) {
            $this->serverErrorTerminate($e->getMessage());
        }
    }

    /**
     * 修改密码接口
     */
    public function updatePassword(Request $request){
        $params = delToken($request->param());
        try {
            $password = $params['password'];
            $StaffModel = new StaffModel();
            $where['staff_id'] = $params['staff_id'] ;
            $updata['salt'] = $StaffModel->generateSalt();
            $updata['password'] = md5( $password. $updata['salt']);
            $StaffModel->where($where)->update($updata);
            $this->successTerminate();
        } catch (Exception $e) {
            $this->serverErrorTerminate($e->getMessage());
        }
    }
    /**
     * 员工离职接口/恢复在职接口
     */
    public function dimission(Request $request){
        $params = delToken($request->param());
        try {
            $StaffModel = new StaffModel();
            $where['staff_id'] = $params['staff_id'] ;
            $updata['dimission_type'] =$params['dimission_type'];
            $StaffModel->where($where)->update($updata);
            $this->successTerminate();
        } catch (Exception $e) {
            $this->serverErrorTerminate($e->getMessage());
        }
    }
    /**
     * 员工禁止登陆接口
     */
    public function loginType(Request $request){
        $params = delToken($request->param());
        try {
            $StaffModel = new StaffModel();
            $where['staff_id'] = $params['staff_id'] ;
            $updata['is_login'] =$params['is_login'];
            $StaffModel->where($where)->update($updata);
            $this->successTerminate();
        } catch (Exception $e) {
            $this->serverErrorTerminate($e->getMessage());
        }
    }
    /**
     * 员工锁定登陆接口
     */
    public function lockAdmittance(Request $request){
        $params = delToken($request->param());
        try {
            $StaffModel = new StaffModel();
            $where['staff_id'] = $params['staff_id'] ;
            $updata['login_lock'] =$params['login_lock'];
            $StaffModel->where($where)->update($updata);
            $this->successTerminate();
        } catch (Exception $e) {
            $this->serverErrorTerminate($e->getMessage());
        }
    }
    /**
     * 员工解除管理员接口
     */
    public function custodian(Request $request){
        $params = delToken($request->param());
        try {
            $StaffModel = new StaffModel();
            $where['staff_id'] = $params['staff_id'] ;
            $updata['sys_custodian'] =$params['sys_custodian'];
            $StaffModel->where($where)->update($updata);
            $this->successTerminate();
        } catch (Exception $e) {
            $this->serverErrorTerminate($e->getMessage());
        }
    }
    /**
     * 员工编码生成接口
     */
    public function getSn(){
        $SN  = new Sn();
        $snS = $SN->getSn('YG');
        $ret = 'E'.date('Ymd').'_'.$snS['0'];
        try {

            $this->successTerminate($ret);
        } catch (Exception $e) {
            $this->serverErrorTerminate($e->getMessage());
        }
    }
    /**
     *修改员工信息接口
     */
    public function update(Request $request){
        $params = delToken($request->param());
        try {
            $user = new User();
            {
                $user->userid = $params['staff_id'];
                $user->name = $params['staff_name'];//名称
                $user->mobile = $params['phone'];//手机
                $user->department = array($params['department_id']);//部门
                $user->position = $params['duty'];//职位
                $user->gender = $params['sex'];//性别
            }
            $this->qiyeweixin->UserUpdate($user);
            $StaffModel = new StaffModel();
            $params['entry_time'] = strtotime($params['entry_time']);
            $params['birthday'] = strtotime($params['birthday']);
            $params['unmber_location'] = isset($params['unmber_location']) ? implode(',',$params['unmber_location']) : null;
            $params['home_location'] = isset($params['home_location']) ? implode(',',$params['home_location']) : null;
            if (isset($params['accessory'])){
                $accessory = $params['accessory'] ;
                unset($params['accessory']);
            }
            $StaffModel->allowField(true)->save($params,['staff_id',$params['staff_id']]);
            $ID = $StaffModel->getLastInsID();
            //附件
            $StaffAccessoryModel = new StaffAccessory();
            $StaffAccessoryDb = $StaffAccessoryModel->StaffAccessoryDb();
            $StaffAccessoryDb->where('staff_id',$params['staff_id'])->delete();
            if(isset($accessory)){
                foreach ($accessory as $v1){
                    $arrAccessory = explode('|',$v1);
                    $addOrderAccessory['accessory_url'] = $arrAccessory[0];
                    $addOrderAccessory['accessory_name'] =$arrAccessory[1];
                    $addOrderAccessory['staff_id'] = $params['staff_id'];
                    $StaffAccessoryDb->insert($addOrderAccessory);
                }
            }
            $this->successTerminate();
        } catch (Exception $e) {
            $this->serverErrorTerminate($e->getMessage());
        }
    }
    /**
     *获取员工信息接口
     */
    public function info(Request $request){
        $params = delToken($request->param());
        try {
            $StaffModel = new StaffModel();
            $StaffDb = $StaffModel->StaffDb();
            $retData = $StaffDb->alias('a')
            ->join('sh_crm_department b','a.department_id = b.department_id')
            ->field('a.*,b.department_name')
            ->where('a.staff_id',$params['staff_id'])->find();

            $retData['entry_time'] = date('Y-m-d', $retData['entry_time']);
            $retData['birthday'] = date('Y-m-d', $retData['birthday']);
            $retData['unmber_location'] = !empty($retData['unmber_location'])?explode(',',$retData['unmber_location']):[];
            $retData['home_location'] = !empty($retData['home_location'])?explode(',',$retData['home_location']):[];
            $retData['superior_name'] = $StaffDb->where('staff_id',$retData['superior_id'])->value('staff_name');
            $StaffAccessoryModel = new StaffAccessory();
            $StaffAccessoryDb = $StaffAccessoryModel->StaffAccessoryDb();
            $aData = $StaffAccessoryDb->where('staff_id',$params['staff_id'])->field('accessory_url url,accessory_name name')->select();
            if(!empty($aData)){
                foreach ($aData as &$v1){
                    $v1['url'] = $v1['url'].'|'.$v1['name'];
                }
                $retData['accessory'] = $aData;
            }
            $this->successTerminate($retData);
        } catch (Exception $e) {
            $this->serverErrorTerminate($e->getMessage());
        }
    }
    /**
     *微信同步
     */
    public function synchronization(){
        //获取微信所有员工
        $defaultPassword = '123456';
        $UserList = $this->qiyeweixin->UserList(1,1);
        $addDatas = [];
        $Staff = new \app\crm\model\Staff();
        $StaffDb = $Staff->StaffDb();
        $pcStaff = $StaffDb->where('is_downstream',1)->column('staff_id,staff_name,phone,department_id,duty,sex','staff_id');

        foreach ($UserList as $k=>$v){
            if (array_key_exists($v->userid,$pcStaff))
            {
                $up['staff_name'] = $v->name;
                $up['phone'] = $v->mobile;
                $up['department_id'] = $v->department[0];
                $up['duty'] = $v->position;
                $up['sex'] = $v->gender;
                $StaffDb->where('staff_id',$v->userid)->update($up);
                unset($pcStaff[$v->userid]);
            }
            else
            {
                $addDatas[] = $v;
            }

        }

        //pc新增
        if(count($addDatas)>0){
            $StaffModel = new \app\crm\model\Staff();
            foreach ($addDatas as $k1=>$v1){
                    $add['is_downstream'] = 1;
                    $add['staff_id'] = $v1->userid;
                    $add['staff_name'] = $v1->name;
                    $add['phone'] = $v1->mobile;
                    $add['department_id'] = $v1->department[0];
                    $add['duty'] = $v1->position;
                    $add['sex'] = $v1->gender;
                    $add['salt']= $StaffModel->generateSalt();
                    $add['password'] = md5( $defaultPassword. $add['salt']);
                    $StaffDb->insert($add);
            }
        }
        //wx新增
        if(count($pcStaff)>0){
            $UserData =  new User();
            foreach ($pcStaff as $k2=>$v2){
                {

                    $UserData->userid = $v2['staff_id'];
                    $UserData->name =  $v2['staff_name'];
                    $UserData->mobile =  $v2['phone'];
                    $UserData->department =  array( $v2['department_id']);
                    $UserData->position =  $v2['duty'];
                    $UserData->gender =  $v2['sex'];
                }
                $this->qiyeweixin->UserCreate($UserData);
            }

        }
    }
    public function synchronizationData(){
        try {
            $Department = new Department();
            $Department->synchronization();
            $this->synchronization();
            $this->successTerminate();
        } catch (Exception $e) {
            $this->serverErrorTerminate($e->getMessage());
        }

    }
    /**
     * 批量删除员工接口
     */

    public function batchDelete(Request $request){
        $params = delToken($request->param());
        try {
            $StaffModel = new StaffModel();
            $where['staff_id'] = ['in',$params['staff_ids']] ;
            $this->qiyeweixin->UserBatchDelete($params['staff_ids']);
            $StaffModel->where($where)->delete();
            $this->successTerminate();
        } catch (Exception $e) {
            $this->serverErrorTerminate($e->getMessage());
        }
    }
    /**
     * 批量修改部门
     */

    public function batchUpdateDepartment(Request $request){
        $params = delToken($request->param());
        try {
            $StaffModel = new StaffModel();
            $user = new User();
            {

                $user->department = array($params['department_id']);
            }
            foreach ($params['staff_ids'] as $staff_id){
                $user->userid = $staff_id;
                $this->qiyeweixin->UserUpdate($user);
            }
            $where['staff_id'] = ['in',$params['staff_ids']] ;
            $StaffModel->where($where)->update(['department_id'=>$params['department_id']]);
            $this->successTerminate();
        } catch (Exception $e) {
            $this->serverErrorTerminate($e->getMessage());
        }

    }

    //登录
    public function login($username, $password, $platform = '')
    {
        try {
            $StaffModel = new \app\crm\model\Staff();
            empty($username)&&\exception('账号不能为空');
            $user = $StaffModel->field('staff_id,staff_name,password,salt,phone,is_login,sys_custodian')
                ->where('user_name', $username)
                ->where('is_downstream',1)
                ->where('is_del',0)
                ->whereOr('staff_name',$username)
                ->whereOr('phone',$username)
                ->find();

            empty($user) && \exception('用户名不存在');
            $user->is_login === 0 && \exception('用户不可用');
            $passwordUser = md5($password . $user->salt);
            $passwordUser === $user->password || \exception('密码错误');
            // 登录成功
            // 生成token & 更新最后登录时间
            $TOKEN  = $this->generateToken();
            $data = [
                'last_login' => time(),
                'token' => $TOKEN,
            ];
            $StaffModel->save($data, [
                'staff_id' => $user->staff_id,
            ]);

            $user->setAttr('token', $data['token']);
            unset($user->password);
            unset($user->salt);
            
            //权限
            $access = $StaffModel->getAccess($user->staff_id);

            $user->setAttr('hasrole',$access['hasrole']);//是否可用crm
            if($access['hasrole']){
                $user->setAttr('is_manager',$access['is_manager']);//是否crm管理员
                $user->setAttr('power',$access['power']);//具体权限
            }

            $this->successTerminate($user);

        } catch (Exception $e) {
            $this->serverErrorTerminate($e->getMessage());
        }
    }

}
